package unit9_10.user.service;

import unit9_10.user.unit.unit_mysql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class userService {
    static Connection connect=null;
    static Statement statement=null;
//    登录
    public static String login(String username,String password) throws Exception{
        String misg="登录失败";
//        连接数据库驱动
        connect= unit_mysql.getConn();
        statement=connect.createStatement();
//        数据库查询语句
        String sql="select * from user where user='"+username+"' and password='"+password+"'";
//      启动查询
        ResultSet resultSet=statement.executeQuery(sql);
        while(resultSet.next()){
            misg="登陆成功";
        }
        connect.close();
        statement.close();
        return misg;
    }

//    注册
    public static String register(String username,String pw) throws Exception{
        String msg="注册失败";

//        查询用户是否存在
        String result=findUserName(username);
        if(!result.equals("已存在")){
//            编写sql语句
            String sql="insert into user (user,password) values('"+username+"','"+pw+"');";

//            执行sql语句
            statement.execute(sql);
            msg="注册成功";
        }
        return msg;
    }

//    查询用户名是否存在
    public static String findUserName(String username) throws Exception{
        String msg="不存在";
//        编写语句
        String sql="select * from user where user='"+username+"';";
//        启动查询
        connect=unit_mysql.getConn();
        statement=connect.createStatement();
        ResultSet result=statement.executeQuery(sql);

        while(result.next()){
            msg="已存在";
        }
        return msg;
    }

//    删除用户
    public static String delete(String username,String pw) throws Exception{
        String msg="删除失败";
//        判断用户是否存在
        String result=findUserName(username);
        if(result.equals("已存在")){
            if("登录成功".equals(login(username,pw))){
                //            编写sql语句
                String sql="delete from user where user='"+username+"';";
                statement=connect.createStatement();
                statement.execute(sql);
                msg="删除成功";

            }else{
                System.out.println("密码验证失败");
            }
        }else{
            System.out.println("用户名不存在");
        }
        return msg;
    }
}
